package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.crm.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.GoodsHideRequest;
import com.jmp.base.dto.GoodsPriceRemarkRequest;
import com.jmp.base.dto.GoodsShowRequest;
import com.jmp.feign.GoodsFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.facade.CompanyFacadeService;
import one.stand.mapper.CompanyMapperExtPublic;
import one.stand.mapper.GoodsApiCrmPcMapper;
import one.stand.model.*;
import one.stand.service.*;
import one.stand.util.AssertUtil;
import one.stand.util.DateUtil;
import one.stand.util.OneListUtil;
import one.stand.util.SqlUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("crmPc/company/select")
@Api(description = "优选平台-代理商品")
public class CompanySelectController {

    public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy.MM.dd");

    @Autowired
    private GoodsFeign goodsFeign;

    @Autowired
    private CompanyFacadeService companyFacadeService;
    @Autowired
    private CompanySelectService companySelectService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private OrderInfoBaseService orderInfoBaseService;
    @Autowired
    private CompanyMapperExtPublic companyMapperExtPublic;
    @Autowired
    private GoodsApiCrmPcMapper goodsApiCrmPcMapper;
    @Autowired
    private GoodsBaseService goodsBaseService;

    @PostMapping("/config")
    @ApiOperation(value = "配置")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<CompanySelectConfigResponse> config(@RequestAttribute CompanySelectConfigRequest request) {

        List<Company> companies = companyMapperExtPublic.selectCompanySelectList();
        List<CompanySelectConfigResponse.Company> companyList = ConvertUtils.list(companies, company -> {
            CompanySelectConfigResponse.Company companyRes = CompanySelectConfigResponse.Company.builder()
                    .companyId(company.getCompanyId())
                    .companyName(company.getCompanyName())
                    .goodsNum(goodsApiCrmPcMapper.selectNum(company.getCompanyId()))
                    .build();
            CompanySelect companySelect = companySelectService.get(request.getCId(), company.getCompanyId());
            if (Objects.nonNull(companySelect)) {
                companyRes.setSelectId(companySelect.getId());
                companyRes.setSelectStatus(companySelect.getStatus());
                companyRes.setSelectTime(DateUtil.format(DATE_FORMAT, companySelect.getUpdateTime()));
            }
            return companyRes;
        });

        CompanySelectConfigResponse response = CompanySelectConfigResponse.builder().companyList(companyList).build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "配置-关闭")
    @PostMapping("/config/close")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel configClose(@RequestAttribute CompanySelectConfigCloseRequest request) {
        companyFacadeService.selectClose(request.getSelectId());
        return ResultModel.success();
    }

    @ApiOperation(value = "配置-开通")
    @PostMapping("/config/apply")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel configApply(@RequestAttribute CompanySelectConfigApplyRequest request) {
        companySelectService.apply(request.getCId(), request.getSelectCompanyId());
        return ResultModel.success();
    }

    @ApiOperation(value = "产品分类")
    @PostMapping("/goods/type")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<List<CompanySelectGoodsTypeResponse>> getGoodsTypeInfo(@RequestAttribute CompanySelectGoodsTypeRequest request) {

        List<GoodsType> list = goodsApiCrmPcMapper.selectSelectTypeList(request.getCId(), true);

        List<CompanySelectGoodsTypeResponse> responseList = ConvertUtils.list(list, type -> CompanySelectGoodsTypeResponse.builder()
                .goodstypeId(type.getGoodstypeId())
                .name(type.getGroupName())
                .build());

        return ResultModel.success(responseList);
    }

    @ApiOperation(value = "产品列表")
    @PostMapping("/goods")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<CompanySelectGoodsResponse> goods(@RequestAttribute CompanySelectGoodsRequest request) {

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        String nameLike = SqlUtil.like(request.getName());
        List<Goods> goods = goodsApiCrmPcMapper.selectSelect(request.getCId(), nameLike, request.getCategoryId());
        PageResponse2<CompanySelectGoodsResponse.Goods> goodsList = ConvertUtils.page2(goods, go -> {
            GoodsType goodsType = goodsTypeService.get(go.getGoodstypeId());
            List<GoodSpec> goodSpecs = goodsBaseService.getSpecs(go.getGoodsId());
            List<CompanySelectGoodsResponse.Spec> specList = ConvertUtils.list(goodSpecs, goodSpec -> CompanySelectGoodsResponse.Spec.builder()
                    .specId(goodSpec.getSpecId())
                    .specName(StringUtils.defaultIfBlank(goodSpec.getSpecAttribute(), goodSpec.getSpecName()))
                    .priceBatch(goodSpec.getPriceBatch())
                    .price(goodSpec.getPrice())
                    .priceRemark(goodSpec.getPriceRemark())
                    .build());
            return CompanySelectGoodsResponse.Goods.builder()
                    .goodsId(go.getGoodsId())
                    .goodsName(go.getGoodsName())
                    .goodsTypeName(goodsType.getGroupName())
                    .price(go.getPrice())
                    .goodsNum(go.getCount())
                    .dealNum(orderInfoBaseService.countSales(go.getGoodsId()))
                    .createTime(go.getCreateTime())
                    .showStatus(go.getIsShow())
                    .showPrice(go.getShowPrice())
                    .isPayment(go.getIsPayment())
                    .specList(specList)
                    .build();
        });

        CompanySelectGoodsResponse response = CompanySelectGoodsResponse.builder().goodsList(goodsList).build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "产品列表-显示")
    @PostMapping("/goods/show")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel goodsShow(@RequestAttribute CompanySelectGoodsShowRequest request) {

        goodsFeign.show(GoodsShowRequest.builder().id(request.getGoodsId()).build());

        return ResultModel.success();
    }

    @ApiOperation(value = "产品列表-隐藏")
    @PostMapping("/goods/hide")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel goodsHide(@RequestAttribute CompanySelectGoodsShowRequest request) {

        goodsFeign.hide(GoodsHideRequest.builder().id(request.getGoodsId()).build());

        return ResultModel.success();
    }

    @ApiOperation(value = "产品列表-编辑价格")
    @PostMapping("/goods/price")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel goodsPrice(@RequestAttribute CompanySelectGoodsPriceRequest request) {

        List<GoodsPriceRemarkRequest.GoodsSpec> specs = Lists.newArrayList();
        if (OneListUtil.isNotEmpty(request.getSpecList())) {
            for (CompanySelectGoodsPriceRequest.Spec spec : request.getSpecList()) {
                if (Objects.isNull(spec.getPriceRemark())) continue;

                GoodsPriceRemarkRequest.GoodsSpec selectSpec = GoodsPriceRemarkRequest.GoodsSpec.builder()
                        .specId(spec.getSpecId())
                        .priceRemark(spec.getPriceRemark())
                        .build();
                specs.add(selectSpec);
            }
        }
        GoodsPriceRemarkRequest goodsPriceRemarkRequest = GoodsPriceRemarkRequest.builder()
                .goodsId(request.getGoodsId())
                .showPrice(request.getShowPrice())
                .isPayment(request.getIsPayment())
                .specs(specs)
                .build();
        ResultModel resultModel = goodsFeign.priceRemark(goodsPriceRemarkRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }
}
